/**
 * Author Toma
 */

(function () {
  var docEl = document.documentElement,
      resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
      ho_bx = document.getElementById('horizontal'),
      recalc = function () {
        docEl.style.fontSize = 20 * (docEl.clientWidth / 375) + 'px';

        var vr = docEl.clientWidth / docEl.clientHeight;
        if (vr <= .54) {
          docEl.setAttribute('class', 'iphonex');
        } else if (vr >= .64) {
          docEl.setAttribute('class', 'min');
        } else {
          docEl.setAttribute('class', '');
        }

        if (window.form_pop) {
          return ho_bx.style.display = 'none';
        }
        ho_bx.style.display = docEl.clientWidth > docEl.clientHeight ? 'block' : 'none';
      };
  window.addEventListener(resizeEvt, recalc, false);
  document.addEventListener('DOMContentLoaded', recalc, false);
})();


$(function () {
  // 时间选择
	var currYear = (new Date()).getFullYear();
	var opt={};
	opt.date = {preset : 'date'};
	opt.datetime = {preset : 'datetime'};
	opt.time = {preset : 'time'};
	opt.default = {
		theme: 'android-ics light', //皮肤样式
		display: 'top', //显示方式 modal
		mode: 'scroller', //日期选择模式
		dateFormat: 'yyyy-mm-dd',
		lang: 'zh',
		showNow: true,
		nowText: "现在",
		startYear: currYear, //开始年份
		endYear: currYear + 10 //结束年份
	};
	$("#datetime").mobiscroll($.extend(opt['date'], opt['default']));

  // swiper
  var swiper = new Swiper('.content_swiper', {
    direction: 'vertical',
    onInit: function (swiper) {
      swiperAnimateCache(swiper);
      swiperAnimate(swiper);
    },
    onSlideChangeEnd: function (swiper) {
      swiperAnimate(swiper);
      window.swiperEnd = swiper.activeIndex === 2;
    },
    onSetTranslate: function(swiper, translate) {
      if (window.swiperEnd) {
        if (translate < (window.swiperTranslate || 0)) {
          $('.form-pop').fadeIn();
          window.form_pop = true;
        }
      }
      window.swiperTranslate = translate;
    }
  });

  var nav = new Swiper('.swiper_nav', {
      slidesPerView: 'auto',
      paginationClickable: true,
      spaceBetween: 10,
      freeMode: true
  });

  var list = new Swiper('.swiper_list', {
      paginationClickable: true,
      centeredSlides: true,
      autoplay: 2500,
      autoplayDisableOnInteraction: false
  });

  var photo = new Swiper('.swiper_photo', {
    pagination: '.swiper-pagination',
    autoplay: 2500,
    paginationClickable: true
  });

  // event
  $('#backup').on('click', function(e) {
    swiper.slideTo(0);
  });

  $('.showform_hk').on('click', function() {
    $('.form-pop').fadeIn();
    window.form_pop = true;
  });
  $('.close').on('click', function() {
    $('.form-pop').fadeOut();
    window.form_pop = false;
  });

  // submit
  var loading = false;
  $('.form-btn').on('click', function() {
    var _this = $(this);
    var f = {};

    if (loading) {
      return
    }

    var ty = $('#ty').prop('checked');
    f.name = $.trim($('#name').val());
    f.phone = $.trim($('#tel').val());
    f.sex = $('#sex').val();
    f.city = $('#city').val();
    f.distributor = $('#distributor').val();
    f.adress = $('#adress').val();
    f.date = $.trim($('#datetime').val());

    if (!f.name) {
      return alert('请输入姓名')
    }

    if (!/^1[3-9]\d{9}$/.test(f.phone)) {
      return alert('请输入正确的手机号')
    }

    if (!f.city) {
      return alert('请选择城市')
    }

    if (!f.distributor) {
      return alert('请选择经销商')
    }

    if (!f.date) {
      return alert('请选择意向购车时间')
    }

    if (!ty) {
      return alert('请同意《英菲尼迪隐私保护政策》')
    }

    loading = true;
    $.post('/sign_up', f).then(function(result) {
      loading = false;
      var res = JSON.parse(result);
      if (res.error) {
        alert(res.msg);
        return
      }

      alert(res.msg);
      $('form')[0].reset();

      window.form_pop = false;
      $('.form-pop').hide();

    }, function() {
      alert('服务器错误，请重试');
    })

  });

  // 联动
  $('#distributor').on('change', function() {
    var _val = $(this).val();
    var _index = 0;

    $(this).find('option').each(function(i, el) {
      if ($(el).val() === _val) {
        _index = i;
      }
    });

    $('#adress').find('option').each(function(i, el) {
      if (_index === i) {
        $(el).prop('selected', true);
      }
    });
  });

  $('#adress').on('change', function() {
    var _val = $(this).val();
    var _index = 0;

    $(this).find('option').each(function(i, el) {
      if ($(el).val() === _val) {
        _index = i;
      }
    });

    $('#distributor').find('option').each(function(i, el) {
      if (_index === i) {
        $(el).prop('selected', true);
      }
    });
  });

});

(function() {
  // 图片加载
  var size = images.length;
  var ed = 0;

  if (!size) {
    end();
    return
  }

  function loading() {
    ++ed;
    document.getElementById('num').innerHTML = (ed / size * 100).toFixed(1) + '%';
    if (ed == size) {
      end()
    }
  }

  function end() {
    document.querySelector('.loading').style.display = 'none';
  }

  for (var i = 0; i < images.length; i++) {
    var image = new Image();
    image.addEventListener('load', function () {
      loading()
    });
    image.addEventListener('error', function () {
      loading()
    });
    image.src = images[i];
  }

})();
